import Vue from 'vue'
import Vuex from 'vuex'
import { setToken, removeToken } from '@/utils/auth'
import { userInfo } from '@/api/user'

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		hasLogin: false,
		location: {
			latitude: 0, // 纬度
			longitude: 0, // 经度
			name: '' // 地址名称
		},
		userInfo: {} // 用户信息
	},
	getter: {},
	mutations: {
		SET_USERINFO: (state, data) => {
			state.hasLogin = JSON.stringify(data) == '{}' ? false : true
			state.userInfo = data
		}
	},
	actions: {
		// 获取用户信息
		getUserInfo({commit, rootState}) {
			return new Promise((resolve, reject) => {
				userInfo().then(res => {
					if (res.code == 200) {
						commit('SET_USERINFO', res.data)
					}
					resolve()
				}).catch(err => {
					reject(err)
				})
			})
		},
		// 用户退出、注销
		logout({ commit }) {
			commit('SET_SYSTEMINFO', {})
			removeToken()
		},
	}
})

export default store
